'use strict';

/**
 * @name HeaderCtrl
 * @author Yud
 */

angular.module('metalabOperationApp').controller('CommentCtrl', ['$scope', '$rootScope', '$state', '$stateParams', 'MetaResources', 'MetaRemind', function($scope, $rootScope, $state, $stateParams, MetaResources, MetaRemind) {
    //样式
    var height = parseInt(angular.element('.meta-sidebar').css("height")) - 400;
    angular.element('.meta-comments').css("height", height + "px");
    //数据
    $scope.commentCtrl = {
        comments: [],
        comment: {
            content: '',
            targetId: $stateParams.id,
            userId: "_self"
        }
    };
    $scope.getCommentsData = function(sort) {
        MetaResources.comment.query({
                'targetId': $stateParams.id,
                '_embed': 'User',
                '_sort': sort
            },
            function(data) {
                $scope.commentCtrl.comments = data;
            },
            function(error) {
                MetaRemind.serverError(error);
            });
    };
    $scope.createComment = function() {
        var data = angular.copy($scope.commentCtrl.comment);
        if ($state.includes('meta.permission.demand')) {
          data.targetType = "Demand";
        }
        if ($state.includes('meta.permission.technology')) {
          data.targetType = "Technology";
        }
        if ($state.includes('meta.permission.project')) {
          data.targetType = "SolutionProcess";
        }
        if ($state.includes('meta.permission.user')) {
          data.targetType = "User";
        }
        if ($state.includes('meta.permission.research')) {
          data.targetType = "Talent";
        }
        MetaResources.comment.save({
                'user_id': $scope.commentCtrl.comment.userId
            }, data,
            function() {
                $scope.getCommentsData(angular.element("#fa-sort-ctrl-comment").hasClass('fa-arrow-up') ? '+created_at' : '-created_at');
                $scope.commentCtrl.comment.content = '';
            },
            function(error) {
                MetaRemind.serverError(error);
            });
    };
    $scope.init = function() {
        $scope.getCommentsData('+created_at');
        angular.element("#fa-sort-ctrl-comment").on('click', function() {
            if (angular.element(this).hasClass('fa-arrow-up')) {
                angular.element(this).removeClass('fa-arrow-up');
                angular.element(this).addClass('fa-arrow-down');
                $scope.getCommentsData('-created_at');
            } else {
                angular.element(this).removeClass('fa-arrow-down');
                angular.element(this).addClass('fa-arrow-up');
                $scope.getCommentsData('+created_at');
            }
        });
    };
    $scope.init();
}]);
